package gbench.appdemo.trading;

import static java.util.stream.Collectors.summarizingDouble;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import gbench.appdemo.trading.position.TradingPositionBill;
import gbench.appdemo.trading.proxy.ServiceProxy;
import gbench.common.tree.LittleTree.IRecord;
import gbench.commonApp.data.DataApp;

public class TradeAllocation {
    
    public class HpChemData extends DataApp{
        
        public void processOrders() {
            cfg.set("url", "jdbc:mysql://localhost:3306/salespro?serverTimezone=GMT%2B8"); reload();
            jdbc.withTransaction(sess->{
                final var orders = sess.sql2records("select * from `order` limit 1000");// 提取订单数据
                final IRecord result= IRecord.pivotTable(orders, 
                      "goods_name,clientele_name", // 对订单数据的阶层化处理
                      stream->stream.collect(summarizingDouble(e->e.dbl("number"))).getSum()
                );// pivotTable
                result.foreach((productName,clientele)->{
                    final var agentNames = ((IRecord)clientele).keys();
                    agentNames.forEach(agentName->{
                        serviceProxy.addAgent(agentName,agent->{
                            serviceProxy.addProduct(productName,agent::addFavorite);
                        });
                    });
                });
            });
        }
    }
    
    private ServiceProxy serviceProxy = ServiceProxy.getInstance();// 获取serviceProxy
    
    public List<TradingPositionBill> getPostions(){
        //serviceProxy.getAgents().get
        return null;
    }
    
    /**
     * 
     */
    public void preparePositions() {
        var agents = serviceProxy.getAgents();
        agents.forEach(agent->{
            for(int i=0;i<10;i++) {// 随机做10个叫头寸
                var position = agent.randPosition();
                serviceProxy.publishTradingPositionBill(position);
            }//for
        });
    }
    
    
    @SuppressWarnings("unused")
    public void alloate() {
        var hpd = this.new HpChemData();
        hpd.processOrders();
        this.preparePositions();
        serviceProxy.getAgents().forEach(agent->{
            var ai = new AtomicInteger(1);
            var bills = agent.getTradingPositionBills().stream()
                .sorted((a,b)->(a.getPosition()+""+a.getQuantity()).compareTo(b.getPosition()+""+b.getQuantity()))
                .collect(Collectors.toList());
            bills.forEach(bill->{
                // System.out.println(ai.getAndIncrement()+")"+bill);
            });
            serviceProxy.trialBalance(bills,e->true);
        });
    }
    
    public static void main(String args[]) {
        var ta = new TradeAllocation();
        ta.alloate();
    }

}
